#!/bin/sh /etc/rc.common
# Copyright (C) 2021-2025 sirpdboy

. "${IPKG_INSTROOT}/lib/functions.sh"

START=99
USE_PROCD=1

EXTRA_COMMANDS="download verify"
EXTRA_HELP=\
"	download	Download Ookla Speedtest-CLI
	verify	Verify Ookla Speedtest-CLI integrity"

OOKLA_SPEEDTEST='/usr/bin/speedtest'
CONFIG='netspeedtest'
log='/tmp/netspeedtest.log'

download() {
    . /etc/openwrt_release
    local url arch=$1
    local proxy=$2 
    [ -z "$arch" ] && arch=$DISTRIB_ARCH
    [ -z "$proxy" ] && proxy='0'

    [ "$proxy" == "1" ] && export ALL_PROXY="http://192.168.10.8:1080"

    UA='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
    url=$( \
        curl --connect-timeout 10 --retry 3 -sSL 'https://www.speedtest.net/apps/cli' \
        --user-agent "$UA" \
        | grep "Download for Linux" \
        | sed 's|<|\n<|g' \
        | sed -n '/Download for Linux/,/<\/div>/p' \
        | sed -En "s|.*<a href=\"([^\"]+)\">${arch}|\1|p" \
    )
    [ -z "$url" ] && { echo "Failed to get download URL" >> "$log"; return 1; }

    # Backup existing file
    [ -f "$OOKLA_SPEEDTEST" ] && mv "$OOKLA_SPEEDTEST" "${OOKLA_SPEEDTEST}.bak"

    if curl -sSL "$url" --user-agent "$UA" | tar -xvz -C /tmp; then
        mkdir -p "${OOKLA_SPEEDTEST%/*}" 2>/dev/null
        cp -f /tmp/speedtest "$OOKLA_SPEEDTEST"
        rm -rf /tmp/speedtest
        chmod 755 "$OOKLA_SPEEDTEST"
        
        if verify; then
            echo "Download successful: $($OOKLA_SPEEDTEST --version | awk '/Speedtest/{print $1" ver:"$4}')" >> "$log"
        else
            echo "Download failed: binary verification failed" >> "$log"
            [ -f "${OOKLA_SPEEDTEST}.bak" ] && mv "${OOKLA_SPEEDTEST}.bak" "$OOKLA_SPEEDTEST"
            return 1
        fi
    else
        echo "Download failed: could not retrieve package" >> "$log"
        [ -f "${OOKLA_SPEEDTEST}.bak" ] && mv "${OOKLA_SPEEDTEST}.bak" "$OOKLA_SPEEDTEST"
        return 1
    fi
    
    unset ALL_PROXY
}

verify() {
    [ -x "$OOKLA_SPEEDTEST" ] && "$OOKLA_SPEEDTEST" --version >/dev/null 2>&1
}

start() {
    if ! verify; then
        download || {
            echo "Critical: Failed to install Speedtest CLI" >> "$log"
            exit 1
        }
    fi
}
restart() {
    start
}
